import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  InputNumber,
  Space,
  Select,
  DatePicker,
  Spin,
  Tabs,
  Row,
  Col,
  Switch
} from "antd";
import type { ColumnsType } from "antd/es/table";
import planService, {
  type PageListReq,
} from "@/api/services/eam/checkMaintailPlanService";
import type { EamCheckMaintainPlan } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import EamCheckMaintainPlanEquipmentPage, {
  type EamCheckMaintainPlanEquipmentHandles,
} from "./equipment";
import EamCheckMaintainPlanProgramPage, {
  type EamCheckMaintainPlanProgramHandles,
} from "./program";
import CustomTable from "@/components/grid/CustomTable";
import dayjs from "dayjs";
const { TextArea } = Input;

export default function EamCheckMaintainPlanPage() {
  const equipmentRef = useRef<EamCheckMaintainPlanEquipmentHandles>(null);
  const programRef = useRef<EamCheckMaintainPlanProgramHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    planName: undefined,
    planType: undefined,
    startDate: undefined,
    endDate: undefined,
    cycleType: undefined,
    periodType: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<EamCheckMaintainPlan[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<EamCheckMaintainPlan | null>(
    null
  );
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const periodTypeOptions = useDictionary("period_type");
  const statusOptions = useDictionary("system_status");
  const typeOptions = useDictionary("equipment_check_maintain_type");

  const columns: ColumnsType<EamCheckMaintainPlan> = [
    {
      title: "计划名称",
      width: 120,
      key: "planName",
      dataIndex: "planName",
    },
    {
      title: "计划类型",
      width: 120,
      key: "planType",
      render: (_, record) => (
        <TableDictTag dictCode="equipment_check_maintain_type" value={record.planType ?? ""} />
      ),
    },
    {
      title: "开始日期",
      width: 120,
      key: "startDate",
      dataIndex: "startDate",
    },
    {
      title: "结束日期",
      width: 120,
      key: "endDate",
      dataIndex: "endDate",
    },
    {
      title: "频率",
      width: 120,
      key: "cycleType",
      dataIndex: "cycleType",
    },
    {
      title: "周期类型",
      width: 120,
      key: "periodType",
      dataIndex: "periodType",
      render: (_, record) => (
        <TableDictTag dictCode="period_type" value={record.periodType ?? ""} />
      ),
    },
    {
			title: "状态",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => (
				<Switch
					checkedChildren="开启"
					unCheckedChildren="关闭"
					checked={record.status === "1"}
					onChange={(checked) => {
						const newStatus = checked ? '1' : '0';
						const data:EamCheckMaintainPlan = {
							...record,
							status: newStatus
						}
						// 调用你的更新函数，例如
						handleStatusChange(data);
					}}
				/>
			),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 180,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleCreateReport(record)}>
            生成任务
          </Button>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    planService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (eamCheckMaintainPlan: EamCheckMaintainPlan) => {
    setEditingData(eamCheckMaintainPlan);
    form.setFieldsValue(eamCheckMaintainPlan);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (eamCheckMaintainPlan: EamCheckMaintainPlan) => {
    setEditingData(eamCheckMaintainPlan);
    form.setFieldsValue(eamCheckMaintainPlan);
    setIsView(true);
    setDrawerVisible(true);
  };

  //生成任务
  const handleCreateReport = async (eamCheckMaintainPlan: EamCheckMaintainPlan) => {
    setLoading(true);
    await planService.createReport(eamCheckMaintainPlan).then(res => {
      toast.success("生成任务成功");
    }).catch(error => {
      toast.error(error.message);
    }).finally(() => {
      setLoading(false);
    });
  }

  //提交表单数据
  const handleSubmit = async (values: EamCheckMaintainPlan) => {
    try {
      setSubmitLoading(true);

      //设备点检保养计划设备信息
      const deleteEquipmentIds = equipmentRef.current?.getDeleteIds();
      const addEquipments = equipmentRef.current?.getAddList();
      const updateEquipments = equipmentRef.current?.getUpdateList();

      //设备点检保养计划项目
      const deleteProgramIds = programRef.current?.getDeleteIds();
      const addPrograms = programRef.current?.getAddList();
      const updatePrograms = programRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteEquipmentIds: deleteEquipmentIds,
        addEquipments: addEquipments,
        updateEquipments: updateEquipments,
        deleteProgramIds: deleteProgramIds,
        addPrograms: addPrograms,
        updatePrograms: updatePrograms,
      };
      if (editingData) {
        await planService.update(data);
        toast.success("更新设备点检保养计划成功");
      } else {
        await planService.add(data);
        toast.success("创建设备点检保养计划成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await planService.remove(selectedRowKeys);
      toast.success("删除设备点检保养计划成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

    const handleStatusChange = async (plan: EamCheckMaintainPlan) => {
      await planService.changeStatus(plan).then(res => {
        toast.success("修改成功");
        fetchPageList();
      }).catch(error => {
        toast.error(error.message);
      })
    }

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="planName" label="计划名称">
            <Input allowClear placeholder="请输入计划名称" />
          </Form.Item>

          <Form.Item name="planType" label="计划类型">
            <Select
              options={typeOptions}
              allowClear
              style={{ width: 170 }}
              placeholder="请选择周期类型"
            />
          </Form.Item>

          <Form.Item name="periodType" label="周期类型">
            <Select
              options={periodTypeOptions}
              allowClear
              style={{ width: 170 }}
              placeholder="请选择周期类型"
            />
          </Form.Item>

          <Form.Item name="status" label="状态">
            <Select
              options={statusOptions}
              allowClear
              style={{ width: 170 }}
              placeholder="请选择周期类型"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑设备点检保养计划" : "新增设备点检保养计划"}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button
                type="primary"
                loading={submitLoading}
                onClick={() => form.submit()}
              >
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item name="planName" label="计划名称">
                <Input placeholder="请输入计划名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="planType"
                label="计划类型"
                rules={[
                  {
                    required: true,
                    message: "请填写计划类型",
                  },
                ]}
              >
                <Select
                  options={typeOptions}
                  allowClear
                  placeholder="请选择周期类型"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="startDate"
                label="开始日期"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endDate"
                label="结束日期"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="cycleType"
                label="频率"
                rules={[
                  {
                    required: true,
                    message: "请填写频率",
                  },
                ]}
              >
                <InputNumber
                  placeholder="请输入频率"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="periodType"
                label="周期类型"
                rules={[
                  {
                    required: true,
                    message: "请填写周期类型",
                  },
                ]}
              >
                <Select options={periodTypeOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "设备信息",
                children: (
                  <EamCheckMaintainPlanEquipmentPage
                    ref={equipmentRef}
                    parentId={editingData?.id}
                  />
                ),
              },
              {
                key: "2",
                label: "点检保养项目",
                children: (
                  <EamCheckMaintainPlanProgramPage
                    ref={programRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>
    </Spin>
  );
}
